<script setup>
import {ElConfigProvider,ElMessage} from "element-plus";
import {onMounted, ref, watch} from "vue";
import {checkSession, getClientId, getSystemInfo} from "@/store/cache.js";
import {isChrome, isMobile} from "@/utils/libs.js";
import {useSharedStore} from "@/store/sharedata.js";
import {getUserToken} from "@/store/session.js";

// 防抖函数，确保回调在连续触发时只执行一次（间隔 200ms），用于优化性能
const debounce = (fn, delay) => {
  let timer
  return (...args) => {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn(...args)
    }, delay)
  }
}

const _ResizeObserver = window.ResizeObserver
// 重写 ResizeObserver：监听元素尺寸变化时，通过防抖减少高频触发导致的性能问题（如窗口调整）。
window.ResizeObserver = class ResizeObserver extends _ResizeObserver {
  constructor(callback) {
    callback = debounce(callback, 200)
    super(callback);
  }
}

const store = useSharedStore()
onMounted(() => {
  // 获取系统参数
  getSystemInfo().then(res => {
    // 创建 link 标签
    const link = document.createElement('link')
    link.rel = 'shortcut icon'
    // // 动态设置网站图标
    link.href = res.data.logo
    document.head.appendChild(link)
  })
  // 如果不是Chrome并且不是手机访问就提示用户
  if (!isChrome() && !isMobile()) {
    ElMessage.info('建议使用 Chrome 浏览器以获得最佳体验。')
  }
  // 检测前台用户是否登录
  checkSession().then(() => {
    store.setIsLogin(true)
  }).catch(() => {
    console.log('前台用户未登录')
  })
  // 设置主题
  document.documentElement.setAttribute("data-theme",store.theme)
})

watch(() => store.isLogin, (val) => {
  if (val) {
    // 前台用户登录后建立 WebSocket 连接
    connect()
  }
})

const handler = ref(0)
// 初始化websocket连接
const connect = () => {
  let host = import.meta.env.VITE_VUE_APP_WS_HOST
  if (host === '') {
    if(location.protocol === 'https:') {
      host = 'wss://' + location.host
    }else{
      host = 'ws://' + location.host
    }
  }
  // 获取一个客户端Id
  const clientId = getClientId()
  const _socket = new WebSocket(host + `/api/chat/ws?client_id=${clientId}`,['token',getUserToken()])
  // 监听连接成功事件
  _socket.addEventListener('open',() => {
    console.log('WebSocket 已连接')
    // 每隔5秒发送一次心跳检测
    handler.value = setInterval(() => {
      if(_socket.readyState === WebSocket.OPEN) {
        _socket.send(JSON.stringify({'type':'ping'}))
      }
    },5000)
  })
  // 监听连接关闭事件
  _socket.addEventListener('close',() => {
    // 清除定时器
    clearTimeout(handler.value)
    // 重新连接
    connect()
  })
  store.setSocket(_socket)
}

</script>


<template>
  <el-config-provider>
    <router-view/>
  </el-config-provider>
</template>

<style lang="stylus">
@import '@/assets/iconfont/iconfont.css'
html, body {
  margin: 0;
  padding: 0;
}

#app {
  margin: 0 !important;
  padding: 0 !important;
  font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;

  --primary-color: #21aa93

  h1 { font-size: 2em; } /* 通常是 2em */
  h2 { font-size: 1.5em; } /* 通常是 1.5em */
  h3 { font-size: 1.17em; } /* 通常是 1.17em */
  h4 { font-size: 1em; } /* 通常是 1em */
  h5 { font-size: 0.83em; } /* 通常是 0.83em */
  h6 { font-size: 0.67em; } /* 通常是 0.67em */
}

.el-overlay-dialog {
  display flex
  justify-content center
  align-items center
  overflow hidden

  .el-dialog {
    margin 0;

    .el-dialog__body {
      //max-height 80vh
      overflow-y auto
    }
  }
}

/* 省略显示 */
.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.van-toast--fail {
  background #fef0f0
  color #f56c6c
}

.van-toast--success {
  background #D6FBCC
  color #07C160
}
</style>
